<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$servername = "localhost";
$username = "root"; // 数据库用户名
$password = "store"; // 数据库密码
$dbname = "aiweb"; // 数据库名称

// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);

// 检查连接
if ($conn->connect_error) {
    echo json_encode(['success' => false, 'message' => '连接失败: ' . $conn->connect_error]);
    exit;
}

// 获取表单数据
$appId = $_POST['appid'] ?? '';
$appName = $_POST['appname'] ?? '';
$appType = $_POST['apptype'] ?? '';
$appInfo = $_POST['appinfo'] ?? '';
$appDetails = $_POST['appdetails'] ?? '';
$appUrl = $_POST['appurl'] ?? '';
$logoUrl = ''; // 用于存储 logo 图片的 URL

// 处理文件上传
if (isset($_FILES['applogo']) && $_FILES['applogo']['error'] == UPLOAD_ERR_OK) {
    $logo = $_FILES['applogo'];
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];  // 允许的文件类型

    if (in_array($logo['type'], $allowedTypes)) {
        $uploadDir = 'uploads/';  // 上传目录
        $logoName = uniqid('logo_', true) . '.' . pathinfo($logo['name'], PATHINFO_EXTENSION);
        $logoPath = $uploadDir . $logoName;

        // 确保上传目录存在
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        // 移动文件到指定目录
        if (move_uploaded_file($logo['tmp_name'], $logoPath)) {
            $logoUrl = 'http://' . $_SERVER['HTTP_HOST'] . '/' . $logoPath;
        } else {
            echo json_encode(['success' => false, 'message' => '文件上传失败，请重试。']);
            exit;
        }
    } else {
        echo json_encode(['success' => false, 'message' => '只允许上传 JPEG、PNG 或 GIF 格式的图片。']);
        exit;
    }
}

// 构建 SQL 查询字符串
if ($logoUrl) {
    $sql = "UPDATE app SET appname = '$appName', type = '$appType', info = '$appInfo', details = '$appDetails', logo = '$logoUrl', url = '$appUrl' WHERE appid = '$appId'";
} else {
    // 如果没有上传 logo，则不更新 logo 字段
    $sql = "UPDATE app SET appname = '$appName', type = '$appType', info = '$appInfo', details = '$appDetails', url = '$appUrl' WHERE appid = '$appId'";
}

// 执行查询
if ($conn->query($sql) === TRUE) {
    $response = ['success' => true];
} else {
    $response = ['success' => false, 'message' => '更新失败: ' . $conn->error];
}

// 关闭连接
$conn->close();

// 返回 JSON 响应
header('Content-Type: application/json');
echo json_encode($response);
?>
